package vn.com.tiz.DocumentZ.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import vn.com.tiz.DocumentZ.utils.LogTools;

import android.net.Uri;
import android.text.format.Time;



public class GetXmlTask  implements Runnable{

	public interface OnGetXmlCompleted{
		public void GetXmlCompleted(String result);
	}
	
	public interface OnGetXmlFail{
		public void GetXmlFail(String error_msg,int error_code);
	}			
	
	private String m_url;
	private int m_TimeOut = 5000; // default timeout la 10 000 ms(10 seconds).
	
	private OnGetXmlCompleted m_OnGetXmlCompleted;
	private OnGetXmlFail m_OngetXmlFail;
	
	public void setOnGetXmlCompleted(OnGetXmlCompleted handler){
		m_OnGetXmlCompleted = handler;
	}
	
	public void setOnGetXmlFail(OnGetXmlFail handler){
		m_OngetXmlFail = handler;
	}
	
	public GetXmlTask(String url){
		m_url = url;
	}
	
	public GetXmlTask(String url,int timeout){
		m_url = url;
		m_TimeOut = timeout;
	}

	
	private String send(String host, String path, List<BasicNameValuePair> postParams, boolean useSSL, int portNo) throws Exception {
		if (useSSL) {
			portNo = 80;
		}
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), portNo));

		if (useSSL) {
			SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
			schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
		}
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

		Uri.Builder uriBuilder = new Uri.Builder();
		uriBuilder.path("/" + path);

		if (useSSL) {
			portNo = 443;
		}
		DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
		HttpResponse response;
		if (postParams != null) {
			HttpPost method = new HttpPost(uriBuilder.build().toString());

			method.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
			response = client.execute(new HttpHost(host, portNo, useSSL?"https":"http"), method);
		} else {
			HttpGet method = new HttpGet("/"+path);
			response = client.execute(new HttpHost(host, portNo, useSSL?"https":"http"), method);
		}
		StatusLine statusLine = response.getStatusLine();
		if (statusLine == null) {
			throw new Exception("Http error response:unknown");
		}
		int status = statusLine.getStatusCode();
		if (status != HttpStatus.SC_OK) {
			throw new Exception("Http error response:"+status);
		}
		HttpEntity entity = response.getEntity();
		if (entity == null) {
			throw new Exception("Http error:no data");
		}
		return EntityUtils.toString(entity, "UTF-8");
	}
	
	private String HttpGetXml(String url){
		String result = "";
		long tim1 = System.currentTimeMillis();
		//httpc
		url = "http://staging-spapi.disney.co.jp/AppAPI/V2.0/ApplicationInformation/GetVersionInfo?AppId=1000009&OutputDivision=1&CarrierCategory=4&PackageName=jp.co.disney.disneymobile.calculator";
		String host = "staging-spapi.disney.co.jp";
		String path ="AppAPI/V2.0/ApplicationInformation/GetVersionInfo?AppId=1000009&OutputDivision=1&CarrierCategory=4&PackageName=jp.co.disney.disneymobile.calculator";
		//String path
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

//		if (useSSL) {
//			SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
//			schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
//		}
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		
		
		HttpConnectionParams.setConnectionTimeout(params, m_TimeOut);	// Set the timeout in milliseconds until a connection is established.

		HttpResponse response;
		
		// in milliseconds which is the timeout for waiting for data.
		HttpConnectionParams.setSoTimeout(params, m_TimeOut);// in milliseconds which is the timeout for waiting for data.

		
		DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
		//client.getParams().setParameter("http.socket.timeout", 5000);//5s
		try {
		
			//this.sleep(5000);
			//Thread.sleep(2000);
			HttpGet httpmethod = new HttpGet("/"+path);
	
			//httpmethod.s
			response = client.execute(new HttpHost(host, 80, "http"), httpmethod);
			
			//client.
			//client.getParams().setParameter(name, value)
			HttpEntity entity = response.getEntity();
			
			result = EntityUtils.toString(entity,"UTF-8");
			if(m_OnGetXmlCompleted != null) m_OnGetXmlCompleted.GetXmlCompleted(result);
			
			long tim2 = System.currentTimeMillis();
			long p = tim2 - tim1;
			
			LogTools.info("Complete in :"+p+"ms");
			
		}catch (UnknownHostException ex) {
			// TODO: handle exception
			long tim2 = System.currentTimeMillis();
			long p = tim2 - tim1;
			
			LogTools.info("Host not found :"+p+"ms");
			
		}catch (ConnectTimeoutException ex1) {
			// TODO: handle exception
			long tim2 = System.currentTimeMillis();
			long p = tim2 - tim1;
			LogTools.info("Connection Time out :"+p+"ms");
		}catch (SocketTimeoutException ex2) {
			// TODO: handle exception
			long tim2 = System.currentTimeMillis();
			long p = tim2 - tim1;
			LogTools.info("Connection Socket Time out :"+p+"ms");
		}
		
		catch (Exception e) {
			// TODO: handle exception
			long tim2 = System.currentTimeMillis();
			long p = tim2 - tim1;
			LogTools.info("unknow error :"+p+"ms");
			e.printStackTrace();
		}
		
		//response.g
		
		return result;
	}
	
	/**
	 * mot method get xml tu url.
	 * @param urlinput
	 * @return
	 */
	private String DownloadText(String urlinput)
    {
		String str = null;
    	try {
    	    // Create a URL for the desired page
    	    URL url = new URL(urlinput);

    	    // Read all the text returned by the server
    	    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    	   
    	    while ((str = in.readLine()) != null) {
    	        // str is one line of text; readLine() strips the newline character(s)
    	    	//str = str+str;
    	    	//Log.e("Trungbb","tui day ne  "+str);
    	    	 in.close();
    	    	 return str;
    	    }
    	    in.close();
    	    return str;
    	} catch (MalformedURLException e) {
    		e.printStackTrace();
    	} catch (IOException e) 
    	{
    		e.printStackTrace();
    	}
    	  return str;
    }

	public void run() {
		// TODO Auto-generated method stub
	   HttpGetXml("");
		
	}
}
